<template>
  <div class="scenario-data-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="text" 
          @click="goBack"
          class="back-button"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="header-content">
          <h1 class="page-title">{{ scenarioName }}</h1>
          <p class="page-subtitle">管理场景数据和相关文档</p>
        </div>
      </div>
      <div class="header-actions">
        <el-button 
          type="info" 
          @click="refreshData"
          class="action-btn"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button 
          type="success" 
          @click="handleExcelEdit"
          class="action-btn"
        >
          <el-icon><Document /></el-icon>
          在Excel表格中编辑
        </el-button>
        <el-button 
          type="primary" 
          @click="handleDocumentManage"
          class="action-btn"
        >
          <el-icon><Folder /></el-icon>
          文档管理
        </el-button>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="data-content">
      <div class="content-header">
        <h2>数据列表</h2>
      </div>

      <!-- 数据表格 -->
      <el-table 
        :data="dataList" 
        style="width: 100%"
        class="data-table"
        stripe
        border
        v-loading="loading"
        element-loading-text="正在加载数据..."
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag size="small" :type="getCategoryType(scope.row.category)">
              {{ scope.row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              size="small" 
              :type="scope.row.status === '已发布' ? 'success' : 'warning'"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleDelete(scope.row)"
              class="delete-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="dataList.length === 0" class="empty-state">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from 'axios'

export default {
  name: 'ScenarioDataDetail',
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 页面数据
    const scenarioName = ref('')
    const scenarioId = ref('')
    const tableId = ref('')
    
    // 表格数据
    const dataList = ref([])
    const tableFields = ref([])
    const loading = ref(false)
    
    // 分页数据
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // API配置
    const API_CONFIG = {
      baseUrl: '/api/v1/tables',
      authorization: 'Bearer app-OFk8vj2CnslsVRKjr2mAtJEr'
    }

    // 初始化页面数据
    onMounted(async () => {
      scenarioId.value = route.query.id || ''
      scenarioName.value = route.query.name || '场景数据详情'
      tableId.value = route.query.tableId || 'default-table-id'
      
      // 加载表格数据
      await loadTableData()
    })

    // 加载表格数据
    const loadTableData = async () => {
      loading.value = true
      try {
        // 首先获取表头信息
        await fetchTableFields()
        // 然后获取表格记录
        await fetchTableRecords()
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败，请检查网络连接')
        // 如果API调用失败，使用模拟数据
        loadMockData()
      } finally {
        loading.value = false
      }
    }

    // 获取表头信息
    const fetchTableFields = async () => {
      try {
        const response = await axios.get(`${API_CONFIG.baseUrl}/${tableId.value}/field`)
        tableFields.value = response.data || []
      } catch (error) {
        console.error('获取表头失败:', error)
        throw error
      }
    }

    // 获取表格记录
    const fetchTableRecords = async () => {
      try {
        const response = await axios.get(`${API_CONFIG.baseUrl}/${tableId.value}/record`)
        if (response.data && response.data.records) {
          dataList.value = response.data.records.map((record, index) => ({
            id: record.id || index + 1,
            ...record.fields,
            // 添加一些默认字段以保持兼容性
            title: record.fields['标题'] || record.fields['title'] || `记录 ${index + 1}`,
            content: record.fields['内容'] || record.fields['content'] || '',
            category: record.fields['分类'] || record.fields['category'] || '未分类',
            status: record.fields['状态'] || record.fields['status'] || '未知',
            updateTime: record.fields['更新时间'] || record.fields['updateTime'] || new Date().toLocaleString()
          }))
          total.value = dataList.value.length
        }
      } catch (error) {
        console.error('获取表格记录失败:', error)
        throw error
      }
    }

    // 加载模拟数据（当API调用失败时使用）
    const loadMockData = () => {
      dataList.value = [
        {
          id: 1,
          title: '小学入学政策',
          content: '详细介绍小学入学的相关政策和要求，包括年龄限制、户籍要求等',
          category: '政策文件',
          status: '已发布',
          updateTime: '2024-01-15 14:30'
        },
        {
          id: 2,
          title: '学区划分标准',
          content: '各区域学区划分的具体标准和范围说明',
          category: '划分标准',
          status: '草稿',
          updateTime: '2024-01-14 16:45'
        },
        {
          id: 3,
          title: '入学申请流程',
          content: '从申请到录取的完整流程说明和注意事项',
          category: '流程指南',
          status: '已发布',
          updateTime: '2024-01-13 10:20'
        },
        {
          id: 4,
          title: '特殊情况处理',
          content: '针对特殊情况的入学政策和处理方式',
          category: '特殊政策',
          status: '已发布',
          updateTime: '2024-01-12 09:15'
        }
      ]
      total.value = dataList.value.length
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // Excel编辑
    const handleExcelEdit = () => {
      ElMessage.success('正在打开Excel编辑器...')
      // 这里可以实现Excel编辑功能
    }

    // 文档管理
    const handleDocumentManage = () => {
      ElMessage.info('跳转到文档管理页面')
      // 这里可以跳转到文档管理页面
    }

    // 查看数据
    const handleView = (row) => {
      ElMessage.info(`查看数据: ${row.title}`)
    }

    // 编辑数据
    const handleEdit = (row) => {
      ElMessage.info(`编辑数据: ${row.title}`)
    }

    // 删除数据
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除"${row.title}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        ElMessage.success('删除成功')
        // 这里可以实现删除逻辑
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }

    // 获取分类标签类型
    const getCategoryType = (category) => {
      const typeMap = {
        '政策文件': 'primary',
        '划分标准': 'success',
        '流程指南': 'warning',
        '特殊政策': 'danger'
      }
      return typeMap[category] || 'info'
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      // 重新加载数据
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      // 重新加载数据
    }

    // 刷新数据
    const refreshData = async () => {
      await loadTableData()
      ElMessage.success('数据已刷新')
    }

    return {
      scenarioName,
      scenarioId,
      tableId,
      dataList,
      tableFields,
      loading,
      currentPage,
      pageSize,
      total,
      goBack,
      handleExcelEdit,
      handleDocumentManage,
      handleView,
      handleEdit,
      handleDelete,
      getCategoryType,
      handleSizeChange,
      handleCurrentChange,
      refreshData,
      loadTableData
    }
  }
}
</script>

<style scoped>
.scenario-data-detail {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
  font-size: 14px;
  margin-top: 4px;
}

.back-button:hover {
  color: #409eff;
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

.data-content {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.data-table {
  margin-bottom: 20px;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f56c6c;
  background-color: #fef0f0;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-left {
    width: 100%;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .content-header {
    margin-bottom: 20px;
  }
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-empty__description) {
  margin-bottom: 20px;
}
</style>